package com.soft.line.aop;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.soft.line.entity.UserInfo;
import com.soft.line.filter.HttpRequestUtil;
import com.soft.line.filter.UserTokenDto;
import com.soft.line.mapper.UserInfoMapper;
import com.soft.line.util.exception.CommonResult;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.implementation.bytecode.Throw;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 注解@Permission 业务逻辑
 * @author wu.xueqiao on 2020/5/12.
 * @version 0.1
 */

@Aspect
@Slf4j
@Component
@ResponseBody
public class PermissionAspect {


    @Autowired
    private UserInfoMapper userInfoMapper;

    //环绕通知
    @Around(value="@annotation(permission)")
    public Object checkPermission(ProceedingJoinPoint joinPoint, Permission permission) throws Throwable{
        //获取请求token中的人员信息，判断人员所具有的权限，权限符合则继续，不符合则抛出相关提醒；
        log.info("------开始校验用户操作权限------");
        //获取请求客户端的个人信息
        UserTokenDto userToken=HttpRequestUtil.getUserToken();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletResponse response=((ServletRequestAttributes)requestAttributes).getResponse();
        Map<String,String> map=new HashMap<>();
        String userName=userToken.getUserInfo().getUserName();
        String password=userToken.getUserInfo().getPassword();
        map.put("username",userName);
        map.put("password",password);
      //  log.info(userToken.getUserName());
        //根据角色,编辑业务逻辑。。。。。
        UserInfo userInfo=userInfoMapper.userLogin(map);
        Object o=null;
        //判断该 用户 的角色id
        if(userInfo.getRoleId()==1){
            //符合角色要求 继续执行
            o=joinPoint.proceed();
        }else {
            //封装无操作权限 返回数据
            response.setHeader("Content-type","application/json; charset=UTF-8");
            OutputStream outputStream=response.getOutputStream();
            CommonResult commonResult=CommonResult.failed("err：您没有该权限");
            outputStream.write(new ObjectMapper().writeValueAsString(commonResult).getBytes("UTF-8"));
        }
        return o;

    }

}
